ActiveAdmin.register RefundApplication do
  actions :index
  filter :member_name, as: :string
  filter :order_id, label: '订单号'
  scope '1-课程', :ct_order, default: true, show_count: false
  scope '2-训练营', :cp_order, show_count: false
  scope '3-培训', :tr_order, show_count: false
  scope '4-活动', :campaign_order, show_count: false

  index do
    selectable_column
    column :member_name
    column '订单号' do |a|
      link_to a.order_id, admin_order_path(a.order_id, order_type: a.order_type)
    end
    column '订单来源' do |a|
      status_tag(a.order_source, class: :ok)
    end
    column '金额' do |a|
      number_to_currency(a.amount, unit: '￥')
    end
    column :pay_type
    column :operator_i18n
    column :status do |t|
      case t.status
      when "pending"
        status_tag('申请中', class: :ok)
      when "agreed"
        status_tag('已批', class: :red)
      when "refused"
        status_tag('打回', class: :yellow)
      else
        ''
      end
    end
    column :created_at
    column :updated_at
    actions do |t|
      if t.pending?
        link_to("同意", admin_agree_refund_path(t, order_type: t.order_type), method: :post, data: {confirm: '确定要同意该退款申请吗?'}) +
            link_to("打回", admin_refuse_refund_path(t, order_type: t.order_type), method: :post, data: {confirm: '确定要打回该退款申请吗?'})
      end
    end
  end

  controller do
    def agree
      refund_application = RefundApplication.find_by(id: params[:id])
      begin
        RefundApplication.transaction do
          refund_application.update(status: :agreed)
          clazz = (refund_application.order_type.eql?("CampaignsOrder") ? "Campaigns::Order" : refund_application.order_type).constantize
          running_account = clazz.send(:find_by, {order_no: refund_application.order_id}).running_account
          running_account.update(status: :refunded)
          flash[:notice] = "退款成功"
        end
      rescue RuntimeError
        flash[:error] = "退款失败"
      end
      redirect_to collection_path
    end

    def refuse
      refund_application = RefundApplication.find_by(id: params[:id])
      refund_application.update(status: :refused)
      flash[:notice] = '请求打回成功'
      redirect_to collection_path
    end
  end
end
